package com.hpin.mlxteacher.base;

import android.app.Activity;
import android.app.Application;
import android.content.Intent;
import android.graphics.Bitmap;
import android.text.TextUtils;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.baidu.mapapi.SDKInitializer;
import com.hpin.mlxteacher.bean.EmoBean;
import com.hpin.mlxteacher.mqtt.MQTTService;
import com.hpin.mlxteacher.mqtt.MqttManager;
import com.hpin.mlxteacher.mqttsource.MqttException;
import com.hpin.mlxteacher.utils.ParserBrowXml;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;

import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;

/**
 * Created by Aaron on 2015/7/27.
 */
public class MyApplication extends Application {

    public static final String TAG = MyApplication.class.getSimpleName();

    private Intent serviceIntent;
    private HashMap<String, String> emos;
    private List<EmoBean> emoBeanList;
//    public SharedPreferences sp;

    private RequestQueue mRequestQueue;

    public static MyApplication instance = null;

    public static MyApplication getInstance() {
        return instance;
    }

    // 存放activity
    private List<Activity> activityList = new LinkedList<Activity>();
    /**
     * 我的定位坐标的点
     */
    public double myLatitude;
    public double myLongitude;

//    public DisplayImageOptions options;

    public void onCreate() {

        super.onCreate();
        instance = this;
//		// imageload 加载图片
        ImageLoader.getInstance().init(getSimpleConfig());

        // 在Appliction里面设置我们的异常处理器为UncaughtExceptionHandler处理器
//		CrashHandler handler = CrashHandler.getInstance();
//		handler.init(getApplicationContext());

        // 注意该方法要再setContentView方法之前实现 百度地图
        // 在使用 SDK 各组间之前初始化 context 信息，传入 ApplicationContext
        SDKInitializer.initialize(getApplicationContext());

//        sp = getSharedPreferences(Constant.CONFIG, MODE_PRIVATE);

        //极光推送
//        JPushInterface.setDebugMode(false);//是否开启debug模式
        JPushInterface.init(this);

        //sharesdk短信验证
//        SMSSDK.initSDK(this,"996a94cb20aa", "9f1222ada3b22d2d90d53d26aa244ad2");

//        options = new DisplayImageOptions.Builder()
//                .showImageOnLoading(R.drawable.icon_default)
//                .showImageForEmptyUri(R.drawable.icon_default)
//                .showImageOnFail(R.drawable.icon_default)
//                .resetViewBeforeLoading(true)
//                .cacheOnDisk(true).cacheInMemory(true)
//                .cacheOnDisc(true).imageScaleType(ImageScaleType.EXACTLY)
//                .bitmapConfig(Bitmap.Config.RGB_565)
//                .considerExifParams(true)
//                .displayer(new SimpleBitmapDisplayer()).build();

//        //友盟 禁止默认的页面统计方式
//        MobclickAgent.openActivityDurationTrack(false);

    }

    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
//            mRequestQueue = Volley.newRequestQueue(getApplicationContext(), new OkHttpStack(new OkHttpClient()));
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }

        return mRequestQueue;
    }

    //添加到请求队列
    public <T> void addToRequestQueue(Request<T> req, String tag) {
        // set the default tag if tag is empty
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
        //设置超时时间
        req.setRetryPolicy(new DefaultRetryPolicy(6 * 1000, 1, 1.0f));
        req.setShouldCache(false);
        getRequestQueue().add(req);
    }

    //从请求队列中删除
    public void cancelPendingRequests(Object tag) {
        getRequestQueue().cancelAll(tag);
    }

    /**
     * 比较常用的配置方案
     *
     * @return
     */
    private ImageLoaderConfiguration getSimpleConfig() {

        DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
                .cacheInMemory(true).cacheOnDisc(true)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .imageScaleType(ImageScaleType.IN_SAMPLE_INT).build();

        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
                getApplicationContext())
                .threadPoolSize(2)
                // 线程池内加载的数量
                .threadPriority(Thread.NORM_PRIORITY - 2)
                .denyCacheImageMultipleSizesInMemory()
                .memoryCache(new WeakMemoryCache())
                .memoryCacheSize(20 * 1024 * 1024)
//				.discCache(ne)
                .discCacheSize(50 * 1024 * 1024).discCacheFileCount(100)
                // 缓存的文件数量
                .defaultDisplayImageOptions(defaultOptions)
                .imageDownloader(
                        new BaseImageDownloader(getApplicationContext(),
                                5 * 1000, 30 * 1000)) // connectTimeout
//								.writeDebugLogs()
                .build();// 开始构建

        return config;
    }

    // 添加Activity 到容器中
    public void addActivity(Activity activity) {
        activityList.add(activity);
    }


    /**
     * 获取表情的map集合 key是表情的匹配符如[满意], value是图片的名称
     *
     * @return
     */
    public Map<String, String> getEmoMap() {

        if (emos == null || emos.size() == 0) {

            try {
                emos = ParserBrowXml.getInfo(getResources().getAssets().open("brow.xml"));
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }

        return emos;

    }

    /**
     * 获取表情的list集合
     *
     * @return
     */
    public List<EmoBean> getEmoList() {

        if (emoBeanList == null || emoBeanList.size() == 0) {
            try {
                emoBeanList = ParserBrowXml.getListInfo(getResources().getAssets().open("brow.xml"));
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }

        return emoBeanList;
    }

    //启动服务, 登录mqtt
    public void loginMqtt() {

        serviceIntent = new Intent(this, MQTTService.class);
        startService(serviceIntent);

    }

    public void exitMqtt() throws MqttException {

        if (MqttManager.getInstance().getMqttClient() != null && MqttManager.getInstance().getMqttClient().isConnected())
            MqttManager.getInstance().getMqttClient().disconnect();

        if (serviceIntent != null)
            stopService(serviceIntent);
    }


    public void exit() {

        try {

            if (MqttManager.getInstance().getMqttClient() != null && MqttManager.getInstance().getMqttClient().isConnected())
                MqttManager.getInstance().getMqttClient().disconnect();

            //关闭聊天服务
            exitMqtt();

            for (Activity activity : activityList) {
                if (activity != null)
                    activity.finish();

            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            // 友盟统计
//            MobclickAgent.onKillProcess(this);
            System.exit(0);
        }

    }

    public void clearActivity() {

        try {
            for (Activity activity : activityList) {
                if (activity != null)
                    activity.finish();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
